package com.yami.shop.seckill.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.OrderType;
import com.yami.shop.bean.event.PaySuccessHandleOrderStockEvent;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.order.PaySuccessOrderOrder;
import com.yami.shop.seckill.common.dao.SeckillOrderMapper;
import com.yami.shop.seckill.common.model.Seckill;
import com.yami.shop.seckill.common.model.SeckillOrder;
import com.yami.shop.seckill.common.service.SeckillService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 秒杀成功回调
 * @author LGH
 */
@Component("paySuccessHandleOrderStockListener")
@AllArgsConstructor
public class PaySuccessHandleOrderStockListener {

    private final SeckillService seckillService;
    private final SeckillOrderMapper seckillOrderMapper;

    /**
     * 更新秒杀状态
     */
    @EventListener(PaySuccessHandleOrderStockEvent.class)
    @Order(PaySuccessOrderOrder.SECKILL)
    public void seckillPaySuccessListener(PaySuccessHandleOrderStockEvent event) {
        com.yami.shop.bean.model.Order order = event.getOrder();
        if (!Objects.equals(order.getOrderType(), OrderType.SECKILL.value())) {
            return;
        }
        OrderItem orderItem = order.getOrderItems().get(0);
        boolean stockCheck = true;
        SeckillOrder seckillOrder = seckillOrderMapper.selectOne(new LambdaQueryWrapper<SeckillOrder>().eq(SeckillOrder::getOrderNumber, orderItem.getOrderNumber()));
        // 秒杀活动信息（来自缓存）
        Seckill seckill = seckillService.getSeckillById(seckillOrder.getSeckillId());
        // 判断之前秒杀的商品有没有超过限制，-1表示商品不限制秒杀数量
        if (!Objects.equals(seckill.getMaxNum(), -1)) {
            int dbCount = seckillOrderMapper.selectNumByUser(seckill.getSeckillId(), seckill.getProdId(), order.getUserId());
            if (seckill.getMaxNum() < orderItem.getProdCount() + dbCount) {
                stockCheck = false;
            }
        }
        // 用户没有达到购买上限，且秒杀商品还有库存，则购买成功
        boolean deductStock = seckillService.handlerSeckillOrderStock(orderItem,seckillOrder);
        if(deductStock && stockCheck){
            event.getSuccessOrderList().add(order);
        }else {
            event.getRefundOrderList().add(order);
        }
    }
}
